<template>
  <div class="main">
    <div class="head">
      <div class="money">
        <div class="money_top">
          <div>
            <p>交易总笔数:</p>
            <p class="num"> {{ totalOrderCount }} </p>
          </div>
        </div>
        <div class="money_bottom">
          <div>
            <p>交易总金额:</p>
            <p class="num">￥ {{ totalCost }}</p>
          </div>
        </div>
      </div>
      <div class="transaction">
        <div class="transaction_top">
          <div>
            <p>商家交易费率:</p>
            <p class="num">0.6%</p>
          </div>
          <div>
            <p>银联费率:</p>
            <p class="num">0.15%</p>
          </div>
        </div>
        <div class="transaction_bottom">
          <div>
            <p>支付宝费率:</p>
            <p class="num">0.3%</p>
          </div>
          <div>
            <p>微信费率:</p>
            <p class="num">0.2%</p>
          </div>
        </div>
      </div>
      <div class="admin">
        <div class="admin_top">
          <img
            src="https://foruda.gitee.com/avatar/1724899953209675858/10720342_zxvahhjad_1724899953.png!avatar30"
            alt="miHoYo">
          <p style="padding-top: 20px;">操作员</p>
        </div>
        <div class="admin_bottom">
          <p>上午好，admin</p>
        </div>
      </div>
    </div>

    <div class="body">
      <div class="statistics">
        <div class="statistics_header">
          <p>交易统计</p>
          <div class="controls">
            <el-select v-model="selectedRange" placeholder="选择日期范围" @change="updateChartData">
              <el-option label="最近3天" value="3days"></el-option>
              <el-option label="最近7天" value="7days"></el-option>
              <el-option label="最近一个月" value="1month"></el-option>
            </el-select>
          </div>
        </div>
        <p style="text-align: right;">单位（元）</p>
        <div class="statistics_histogram" ref="histogramChart"></div>
      </div>
      <div class="pay">
        <div class="pay_header">
          <p>支付方式</p>
          <div class="controls">
            <el-select v-model="selectedRange" placeholder="选择日期范围" @change="updatePieChartData">
              <el-option label="最近3天" value="3days"></el-option>
              <el-option label="最近7天" value="7days"></el-option>
              <el-option label="最近一个月" value="1month"></el-option>
            </el-select>
          </div>
        </div>
        <p style="text-align: right;">单位（笔）</p>
        <div class="statistics_pie" ref="pieChart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const selectedRange = ref('7days')
const histogramChart = ref(null)
const pieChart = ref(null)
let myHistogramChart = null
let myPieChart = null

// 数据集
const dataSets = {
  '3days': { xAxis: [], series1: [], series2: [], pieData: [] },
  '7days': { xAxis: [], series1: [], series2: [], pieData: [] },
  '1month': { xAxis: [], series1: [], series2: [], pieData: [] }
};

// 订单数据处理后的结果
const orderData = ref([]);
const totalCost = ref(0);
const totalOrderCount = ref(0);

// 获取订单数据
async function orderInfo() {
  try {
    const res = await axios.get("api/alipay/getAll");
    const data = res.data.data;

    // 整合相同日期的数据
    const groupedData = data.reduce((acc, item) => {
      const date = item.createDate.split(' ')[0]; // 获取日期部分
      if (!acc[date]) {
        acc[date] = { date, totalCost: 0, orderCount: 0 };
      }
      acc[date].totalCost += parseFloat(item.payCost);
      acc[date].orderCount += 1;
      return acc;
    }, {});

    // 将对象转换为数组并按日期排序
    orderData.value = Object.values(groupedData).sort((a, b) => new Date(a.date) - new Date(b.date));

    // 更新总金额和总订单数
    totalCost.value = orderData.value.reduce((acc, cur) => acc + cur.totalCost, 0);
    totalOrderCount.value = orderData.value.reduce((acc, cur) => acc + cur.orderCount, 0);

    updateDataSets();
    updateChartData();
    updatePieChartData();

  } catch (error) {
    console.error(error);
  }
}

// 更新数据集
function updateDataSets() {
  dataSets['3days'].xAxis = orderData.value.slice(-3).map(item => item.date);
  dataSets['3days'].series1 = orderData.value.slice(-3).map(item => item.totalCost);
  dataSets['3days'].series2 = orderData.value.slice(-3).map(item => item.orderCount);

  dataSets['7days'].xAxis = orderData.value.slice(-7).map(item => item.date);
  dataSets['7days'].series1 = orderData.value.slice(-7).map(item => item.totalCost);
  dataSets['7days'].series2 = orderData.value.slice(-7).map(item => item.orderCount);

  dataSets['1month'].xAxis = orderData.value.slice(-30).map(item => item.date);
  dataSets['1month'].series1 = orderData.value.slice(-30).map(item => item.totalCost);
  dataSets['1month'].series2 = orderData.value.slice(-30).map(item => item.orderCount);
}

// 初始化图表
onMounted(async () => {
  await orderInfo(); // 等待数据加载完成

  nextTick(() => {
    myHistogramChart = echarts.init(histogramChart.value);
    myPieChart = echarts.init(pieChart.value);

    updateChartData();
    updatePieChartData();
  });
});

// 更新柱状图数据
function updateChartData() {
  if (myHistogramChart) {
    const selectedData = dataSets[selectedRange.value];
    const option = {
      title: { text: '交易金额和订单数统计' },
      tooltip: { trigger: 'axis' },
      legend: { data: ['交易金额', '订单数'] },
      xAxis: { type: 'category', data: selectedData.xAxis },
      yAxis: [
        { type: 'value', name: '金额 (元)' },
        { type: 'value', name: '订单数', position: 'right' }
      ],
      series: [
        { name: '交易金额', type: 'bar', data: selectedData.series1 },
        { name: '订单数', type: 'line', yAxisIndex: 1, data: selectedData.series2 }
      ]
    };
    myHistogramChart.setOption(option);
  }
}

// 更新饼图数据
function updatePieChartData() {
  if (myPieChart) {
    const selectedData = dataSets[selectedRange.value];
    const option = {
      tooltip: { trigger: 'item' },
      legend: { orient: 'vertical', left: 'left' },
      series: [
        {
          name: '支付方式',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 48, name: '支付宝' },
            { value: 0, name: '微信' },
            { value: 0, name: '银联' }
          ]
        }
      ]
    };
    myPieChart.setOption(option);
  }
}
</script>
  
<style>
.main {
  height: 100%;
}

.head {
  display: flex;
  justify-content: space-between;
  gap: 70px;
  width: 100%;
}

.body {
  display: flex;
  justify-content: space-between;
  gap: 50px;
  width: 100%;
  margin-top: 50px;
}

p {
  font-size: 24px;
}

.num {
  font-weight: bold;
  padding-top: 30px;
}

.money,
.transaction,
.admin {
  height: 250px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  flex: 1;
  margin-top: 10px;
}

.money,
.transaction {
  flex: 2;
}

.admin {
  flex: 1.5;
}

.money_top,
.money_bottom,
.transaction_top,
.transaction_bottom,
.admin_top,
.admin_bottom {
  display: flex;
  justify-content: space-between;
  gap: 5px;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.admin {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.admin img {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.statistics {
  flex: 2;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.pay {
  flex: 1;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.statistics_header,
.pay_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.statistics .statistics_histogram,
.statistics_pie {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}

.controls {
  text-align: right;
  width: 250px;
}
</style>
 